<template>
  <div class="order-container">
    <div class="order-header">
      <h1 class="page-title">确认订单</h1>
    </div>

    <!-- 收货地址 -->
    <div class="address-section">
      <div class="address-card">
        <div v-if="address" class="address-info">
          <div class="user-info">
            <span class="name">{{ address.recipient }}</span>
            <span class="gender">{{ address.gender === 1 ? '先生' : '女士' }}</span>
            <span class="phone">{{ address.phone }}</span>
          </div>
          <div class="address-detail">
            {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailedAddress }}
          </div>
        </div>
        <div v-else class="no-address">
          <p>请选择收货地址</p>
        </div>
        <button class="change-address-btn" @click="openAddressModal">
          <i class="fas fa-map-marker-alt"></i>
          选择收货地址
        </button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="order-items">
      <div class="section-title">商品信息</div>
      <div class="items-list">
        <div v-for="item in orderItems" :key="item.id" class="order-item">
          <div class="item-image">
            <img :src="item.image" :alt="item.name">
          </div>
          <div class="item-info">
            <h3 class="item-name">{{ item.name }}</h3>
            <div class="item-price-qty">
              <span class="price">¥{{ item.price.toFixed(2) }}</span>
              <span class="quantity">x{{ item.quantity }}</span>
            </div>
          </div>
          <div class="item-total">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 订单备注 -->
    <div class="order-remark">
      <div class="section-title">订单备注</div>
      <textarea 
        v-model="remark" 
        placeholder="请输入订单备注信息（选填）"
        class="remark-input"
      ></textarea>
    </div>

    <!-- 支付方式 -->
    <div class="payment-section">
      <div class="section-title">支付方式</div>
      <div class="payment-options">
        <label class="payment-option" :class="{ active: paymentMethod === 'wechat' }">
          <input 
            type="radio" 
            name="payment" 
            value="wechat" 
            v-model="paymentMethod"
          >
          <span class="payment-icon">💚</span>
          <span class="payment-name">微信支付</span>
        </label>
        <label class="payment-option" :class="{ active: paymentMethod === 'alipay' }">
          <input 
            type="radio" 
            name="payment" 
            value="alipay" 
            v-model="paymentMethod"
          >
          <span class="payment-icon">💙</span>
          <span class="payment-name">支付宝</span>
        </label>
      </div>
    </div>

    <!-- 订单底部 -->
    <div class="order-footer">
      <div class="price-summary">
        <div class="price-item">
          <span>商品总额</span>
          <span>¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="price-item">
          <span>配送费</span>
          <span>¥{{ deliveryFee.toFixed(2) }}</span>
        </div>
        <div class="price-item total">
          <span>应付总额</span>
          <span class="total-price">¥{{ (totalPrice + deliveryFee).toFixed(2) }}</span>
        </div>
      </div>
      <button class="pay-btn" @click="handlePayment">
        去支付
      </button>
    </div>

    <!-- 地址选择弹窗 -->
    <div class="address-modal" v-if="showAddressModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择收货地址</h3>
          <button class="close-btn" @click="showAddressModal = false">×</button>
        </div>
        <div class="address-list">
          <div 
            v-for="addr in addressList" 
            :key="addr.id"
            class="address-item"
            :class="{ active: address && address.id === addr.id }"
            @click="selectAddress(addr)"
          >
            <div class="address-info">
              <div class="user-info">
                <span class="name">{{ addr.recipient }}</span>
                <span class="gender">{{ addr.gender === 1 ? '先生' : '女士' }}</span>
                <span class="phone">{{ addr.phone }}</span>
              </div>
              <div class="address-detail">
                {{ addr.province }} {{ addr.city }} {{ addr.district }} {{ addr.detailedAddress }}
              </div>
            </div>
          </div>
          <div v-if="addressList.length === 0" class="no-address">
            <p>暂无收货地址</p>
            <router-link to="/address" class="add-address-btn">添加收货地址</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { addOrder } from '../../axios/order'
import { getDefaultAddress, getAddressList } from '../../axios/address'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 订单商品列表
const orderItems = ref([])

// 从路由参数获取选中的商品
const getSelectedItems = () => {
  const items = route.query.items
  if (items) {
    try {
      // 解析JSON字符串为对象
      const parsedItems = JSON.parse(items)
      console.log('解析的商品数据:', parsedItems)
      
      if (!Array.isArray(parsedItems) || parsedItems.length === 0) {
        ElMessage.error('商品数据格式错误')
        return
      }

      orderItems.value = parsedItems
    } catch (err) {
      console.error('解析选中商品数据失败:', err)
      ElMessage.error('获取商品信息失败')
    }
  } else {
    ElMessage.warning('未获取到商品数据')
  }
}

// 计算商品总价
const totalPrice = computed(() => {
  return orderItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

// 配送费
const deliveryFee = ref(10)

// 支付方式
const paymentMethod = ref('wechat')

// 订单备注
const remark = ref('')

// 地址相关
const showAddressModal = ref(false)
const address = ref(null)
const addressList = ref([])

// 获取默认地址
const fetchDefaultAddress = async () => {
  try {
    const response = await getDefaultAddress()
    if (response && response.code === 1) {
      // 如果返回的data为空，说明没有默认地址
      if (!response.data) {
        ElMessage.warning('请先添加收货地址')
        return
      }
      address.value = response.data
    } else {
      ElMessage.warning('请先添加收货地址')
    }
  } catch (err) {
    console.error('获取默认地址失败:', err)
    ElMessage.error('获取默认地址失败')
  }
}

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await getAddressList()
    // 直接使用返回的数组数据
    if (Array.isArray(response)) {
      addressList.value = response
      // 如果没有默认地址，自动选择第一个地址
      if (!address.value && addressList.value.length > 0) {
        const defaultAddress = addressList.value.find(addr => addr.isDefault === 1)
        address.value = defaultAddress || addressList.value[0]
      }
    } else {
      ElMessage.warning('获取地址列表失败')
    }
  } catch (err) {
    console.error('获取地址列表失败:', err)
    ElMessage.error('获取地址列表失败')
  }
}

// 选择地址
const selectAddress = (addr) => {
  address.value = addr
  showAddressModal.value = false
}

// 打开地址选择弹窗
const openAddressModal = async () => {
  await fetchAddressList()
  showAddressModal.value = true
}

// 页面加载时获取数据
onMounted(() => {
  fetchDefaultAddress()
  getSelectedItems()
})

// 处理支付
const handlePayment = async () => {
  if (!address.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (!orderItems.value || orderItems.value.length === 0) {
    ElMessage.warning('订单商品不能为空')
    return
  }

  try {
    // 构建订单数据
    const orderData = {
      addressId: address.value.id.toString(), // 转换为字符串，确保Long类型能正确解析
      remark: remark.value || '',
      paymentMethod: paymentMethod.value || 'wechat',
      // 将数字转换为字符串，让后端自动转换为 BigDecimal
      totalAmount: (totalPrice.value + deliveryFee.value).toString(),
      actualAmount: (totalPrice.value + deliveryFee.value).toString(),
      status: 0,
      orderItems: orderItems.value.map(item => ({
        productId: item.id.toString(), // 转换为字符串，确保Long类型能正确解析
        productName: item.name,
        productImage: item.image,
        // 将数字转换为字符串，让后端自动转换为 BigDecimal
        price: item.price.toString(),
        quantity: item.quantity,
        subtotal: (item.price * item.quantity).toString()
      }))
    }

    console.log('提交的订单数据:', JSON.stringify(orderData))

    // 调用保存订单接口
    const response = await addOrder(orderData)
    console.log('订单提交响应:', response);
    if (response.code === 1) {
      // 跳转到确认支付页面
      router.push({
        name: 'payment-confirm',
        query: {
          orderId: response.data.id
        }
      })
    } else {
      ElMessage.error(response.msg || '创建订单失败')
    }
  } catch (err) {
    console.error('创建订单失败:', err)
    ElMessage.error('创建订单失败，请稍后重试')
  }
}
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 0;
}

/* 地址部分 */
.address-section {
  margin-bottom: 30px;
}

.address-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.address-info {
  flex: 1;
}

.user-info {
  margin-bottom: 10px;
}

.name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-right: 10px;
}

.gender {
  color: #666;
  margin-right: 15px;
}

.phone {
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.change-address-btn {
  padding: 10px 20px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.change-address-btn:hover {
  background: #e9ecef;
}

/* 商品列表 */
.order-items {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 20px;
  font-weight: 600;
}

.order-item {
  display: grid;
  grid-template-columns: 100px 1fr auto;
  gap: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 16px;
  color: #2c3e50;
  margin: 0;
}

.item-price-qty {
  display: flex;
  gap: 20px;
  color: #666;
}

.item-total {
  font-size: 18px;
  color: #e74c3c;
  font-weight: 600;
}

/* 订单备注 */
.order-remark {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.remark-input {
  width: 100%;
  height: 100px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}

.remark-input:focus {
  outline: none;
  border-color: #4CAF50;
}

/* 支付方式 */
.payment-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.payment-options {
  display: flex;
  gap: 20px;
}

.payment-option {
  flex: 1;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: all 0.3s;
}

.payment-option.active {
  border-color: #4CAF50;
  background: #f0f9f0;
}

.payment-option input {
  display: none;
}

.payment-icon {
  font-size: 24px;
}

.payment-name {
  font-size: 16px;
  color: #2c3e50;
}

/* 订单底部 */
.order-footer {
  background: white;
  border-radius: 12px;
  padding: 20px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  gap: 40px;
}

.price-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 300px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  color: #666;
  padding: 0 20px;
  align-items: center;
  min-height: 24px;
}

.price-item.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-weight: 600;
  color: #2c3e50;
  min-height: 40px;
}

.total-price {
  color: #e74c3c;
  font-size: 24px;
  margin-left: 20px;
  line-height: 1;
  display: flex;
  align-items: center;
}

.pay-btn {
  padding: 15px 40px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.pay-btn:hover {
  background: #45a049;
  transform: translateY(-2px);
}

/* 地址选择弹窗 */
.address-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
}

.address-list {
  padding: 20px;
}

.address-item {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #4CAF50;
  background: #f0f9f0;
}

.address-item.active {
  border-color: #4CAF50;
  background: #f0f9f0;
}

.no-address {
  text-align: center;
  padding: 20px;
  color: #666;
}

.add-address-btn {
  display: inline-block;
  margin-top: 10px;
  padding: 8px 16px;
  background: #4CAF50;
  color: white;
  border-radius: 4px;
  text-decoration: none;
}

.add-address-btn:hover {
  background: #45a049;
}

@media (max-width: 768px) {
  .address-card {
    flex-direction: column;
    gap: 15px;
  }

  .change-address-btn {
    width: 100%;
    justify-content: center;
  }

  .order-item {
    grid-template-columns: 80px 1fr;
  }

  .item-total {
    grid-column: 2;
    text-align: right;
  }

  .payment-options {
    flex-direction: column;
  }

  .order-footer {
    flex-direction: column;
    gap: 20px;
  }

  .pay-btn {
    width: 100%;
  }
}
</style> 